package com.yunxin.core.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.yunxin.common.result.PageResult;
import com.yunxin.core.application.admin.team.Team;
import com.yunxin.core.application.service.UserQueryAdminService;
import com.yunxin.core.domain.external.channel.ChannelExternalService;
import com.yunxin.core.domain.external.channel.ChannelPromotionInfo;
import com.yunxin.core.application.command.user.UserInfoPageCommand;
import com.yunxin.core.application.dto.user.UserInfoPageDTO;
import com.yunxin.core.application.assembler.UserInfoAssembler;
import com.yunxin.core.infra.persistence.mapper.user.UserInfoExtendMapper;
import com.yunxin.core.infra.persistence.entity.user.UserInfoDO;
import com.yunxin.core.infra.persistence.entity.user.query.condition.UserPageCondition;
import com.yunxin.core.utils.infra.utils.PageQueryUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zero°
 * @since 2023-06-08
 */
@Service
@RequiredArgsConstructor
public class UserQueryAdminServiceImpl implements UserQueryAdminService {

    private final UserInfoExtendMapper userInfoExtendMapper;

    private final ChannelExternalService channelExternalService;

    private final UserInfoAssembler userInfoAssembler;

    @Override
    public PageResult<UserInfoPageDTO> userPageQuery(UserInfoPageCommand command) {
        UserPageCondition condition = userInfoAssembler.formUserPageCommand(command);
        if (Objects.nonNull(command.getChannelId()) && command.getChannelId() > 0) {
            List<String> promotionCodes = channelExternalService.listPromotionCodeByChannelId(command.getChannelId());
            if (CollUtil.isEmpty(promotionCodes)) {
                // 给 -1 是因为根据渠道id查不到推广code，可能该渠道没配置推广信息,不应该查询数据
                promotionCodes = CollUtil.newArrayList("-1");
            }
            condition.setChannelPromotionCodes(promotionCodes);
        }
        long total = userInfoExtendMapper.countUserPageQuery(condition);
        if (total == 0) {
            return PageResult.success(Collections.emptyList(), total);
        }
        condition.setOffset(PageQueryUtils.X.getOffset(command.getPageNum(), command.getPageSize()));
        List<UserInfoDO> results = userInfoExtendMapper.userPageQuery(condition);
        if (CollUtil.isEmpty(results)) {
            return PageResult.success(Collections.emptyList(), total);
        }
        Set<String> promotionCodes = results.stream().map(UserInfoDO::getChannelPromotionCode).collect(Collectors.toSet());
        Map<String, ChannelPromotionInfo> channelPromotionInfoResultMap = channelExternalService.listChannelPromotionInfoByPromotionCodes(promotionCodes).stream().collect(Collectors.toMap(ChannelPromotionInfo::getPromotionCode, Function.identity()));
        List<UserInfoPageDTO> dtoList = results.stream().map(x -> {
            UserInfoPageDTO dto = userInfoAssembler.toUserPageDTO(x);
            dto.setUserPhone(x.getPhone());
            ChannelPromotionInfo channelPromotionInfoResult = channelPromotionInfoResultMap.get(x.getChannelPromotionCode());
            Optional.ofNullable(channelPromotionInfoResult).ifPresent(c -> {
                dto.setChannelId(c.getChannelId());
                dto.setChannelName(c.getChannelName());
                dto.setChannelPromotionName(c.getPromotionName());
            });
            return dto;
        }).toList();
        return PageResult.success(dtoList, total);
    }


    /**
     * 根据订单id查询团队
     *
     * @param ouaaId
     * @return
     */
    @Override
    public List<Team> selectTeamListById(Long ouaaId) {
        return userInfoExtendMapper.selectTeamListById(ouaaId);
    }
}
